import axios from 'axios';
import qs from 'qs';
import { Notify } from 'vant';
import { getAdmin } from '@A/resource/admin';
import { commonUrl } from '@A/resource/https';

// Http 请求客户端
const httpClient = axios.create({
  timeout: 60000,
  baseURL: commonUrl
});
// 请求拦截器
httpClient.interceptors.request.use(request => {

  // 判断是否存token
  // if(getAdmin(localStorage, 'userInfo') && getAdmin(localStorage, 'userInfo').access_token){
  //   request.url = request.url + '&access_token=' + getAdmin(localStorage, 'userInfo').access_token;
  // }

  let param = {};
  // if(getAdmin(sessionStorage,'admin')){
  //   // param = Object.assign({}, getAdmin(sessionStorage,'admin').data[0])
  //   request.headers.userId = getAdmin(sessionStorage,'admin').data[0].teacherId;
  //   param = {
  //     userId: getAdmin(sessionStorage,'admin').data[0].teacherId,
  //     identity: getAdmin(sessionStorage,'admin').data[0].identity,
  //   }
  // }
  if (window.location.href.indexOf('?') !== -1) {
    request.headers.urlAddress = window.location.href.split('?')[0];
  } else {
    request.headers.urlAddress = window.location.href
  }
  // 如果请求体有值且值不为 FormData 格式请求处理为 {data: body} 格式
  if ( request.data !== undefined && !( request.data instanceof FormData || request.data instanceof URLSearchParams ) ) {
    request.data = Object.assign({}, param, request.data);
    if ( request.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8' ) {
      request.data = qs.stringify(request.data)
    }
    if ( request.headers['Content-Type'] === 'multipart/form-data' ) {
      const formData = new FormData();
      Object.keys(request.data).forEach((key) => {
        formData.append(key, request.data[key]);
      });
      request.data = formData
    }
  } else {
    request.params = Object.assign({}, param, request.params);
    if (request.params) {
      for (let key in request.params) {
        if (Array.isArray(request.params[key])) {
          request.paramsSerializer = (params) => {
            return qs.stringify(params, { arrayFormat: 'repeat' });
          };
        }
      }
    }
  }
  return request
});

// 响应拦截器
httpClient.interceptors.response.use(response => {
  // 判断响应的 code 码是否正常
  const responseData = response.data;
  if (responseData.code) {
    if ( responseData.code === '0' ) {
      return Promise.resolve(responseData)
    } else if (responseData.code == '-1') {
      window.localStorage.clear();
      Notify({ type: 'danger', message: '登录失效' });
      window.location.reload();
      return
    } else {
      Notify({ type: 'danger', message: responseData.msg });
      return false
    }
  } else if (!responseData.code) {
    return Promise.resolve(responseData)
  }
  const err = new Error(responseData.msg || response.statusText);
  err.errorCode = responseData.code;
  return Promise.reject(err)
});

class APIClientService {
  /**
   * 发起 Http 请求POST
   * @param url 请求路径，建议以 / 开头
   * @param params 请求参数，可选(data)
   * @param config 默认json，可选参数(string)
   * @param headers 请求头可以不填，可选参数(object)
   * responseType 表示服务器响应的数据类型，可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
   */
  static async REQUESTPOST(url, params, headers, config) {
    return httpClient({
      url: url,
      method: 'POST',
      data: params,
      responseType: config || 'json',
      headers: headers || {}
    })
  }
  /**
   * 发起 Http 请求GET
   * @param url 请求路径，建议以 / 开头
   * @param params 请求参数，可选(data)
   * @param config 默认json，可选参数(string)
   * @param headers 请求头可以不填，可选参数(object)
   * responseType 表示服务器响应的数据类型，可以是 'arraybuffer', 'blob'(导出), 'document', 'json', 'text', 'stream'
   */
  static async REQUESTGET(url, params, headers, config) {
    return httpClient({
      url: url,
      method: 'GET',
      params: params || {},
      responseType: config || 'json',
      headers: headers || {
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
    })
  }

  /**
   * 发起 Http 请求DETELE
   * @param url
   * @param params
   * @param headers
   * @param config
   * @returns {AxiosPromise<any>}
   * @constructor
   */
  static async REQUESTDETELE(url, params, headers, config) {
    return httpClient({
      url: url,
      method: 'DELETE',
      params: params || {},
      responseType: config || 'json',
      headers: headers || {},
    })
  }
  /**
   * 发起 Http 请求PUT
   * @param url
   * @param params
   * @param headers
   * @param config
   * @returns {AxiosPromise<any>}
   * @constructor
   */
  static async REQUESTPUT(url, params, headers, config) {
    return httpClient({
      url: url,
      method: 'PUT',
      data: params,
      responseType: config || 'json',
      headers: headers || {},
    })
  }

  /**
   * 发起 Http fetch 请求POST
   * @param url
   * @param params
   * @returns {Promise<Response>}
   * @constructor
   */
  static async FETCHTPOST( url, params ) {
    return fetch({
      url: axios.defaults.baseURL + url,
      method: 'POST',
      body: JSON.stringify(params),
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
  }
}
export default APIClientService
